﻿using DevExpress.Data.Filtering;
using DevExpress.ExpressApp;
using DevExpress.ExpressApp.Actions;
using DevExpress.Persistent.Base;
using EasyXaf.EntityDesigner.BusinessObjects;
using EasyXaf.EntityDesigner.BusinessObjects.Entities;
using EasyXaf.EntityDesigner.Models;

namespace EasyXaf.EntityDesigner.Controllers;

public class DesignDomainModelViewController : ObjectViewController<ObjectView, DomainModel>
{
    public SimpleAction DesignModelAction { get; }

    public DesignDomainModelViewController()
    {
        TargetViewNesting = Nesting.Root;

        DesignModelAction = new SimpleAction(this, "DesignModelAction", PredefinedCategory.Tools)
        {
            Caption = "设计",
            ImageName = "Action_Edit",
            SelectionDependencyType = SelectionDependencyType.RequireSingleObject,
        };
    }

    protected override void OnActivated()
    {
        base.OnActivated();

        DesignModelAction.Execute += DesignModelAction_Execute;
    }

    protected override void OnDeactivated()
    {
        DesignModelAction.Execute -= DesignModelAction_Execute;

        base.OnDeactivated();
    }

    private void DesignModelAction_Execute(object sender, SimpleActionExecuteEventArgs e)
    {
        ObjectSpace.CommitChanges();

        if (e.CurrentObject is DomainModel domainModel)
        {
            var entityType = typeof(Entity);
            var objectSpace = Application.CreateObjectSpace(entityType);
            domainModel = objectSpace.GetObject(domainModel);
            var listView = Application.CreateListView(objectSpace, entityType, true);
            ((IModelCurrentDomainModel)listView.Model).CurrentDomainModelId = domainModel.Oid;
            CurrentDomainModelUtils.Save(domainModel.Oid);
            listView.CollectionSource.Criteria["DomainModel"] = CriteriaOperator.Parse("[EntityDesigns][[DomainModel]=?]", domainModel);
            var showViewParameters = new ShowViewParameters(listView)
            {
                TargetWindow = TargetWindow.Current,
            };
            Application.ShowViewStrategy.ShowView(showViewParameters, new ShowViewSource(Frame, DesignModelAction));
        }
    }
}
